package com.leetcode.sorts.arrays.matrix;

import java.util.Arrays;

/**
 * @Author: WuPeng
 * @Date: 2021/5/22 3:32 下午
 *
 * 剑指offer29：顺时针打印矩阵
 *
 */
public class ClockwisePrintMatrix {

    public static int[] solution(int[][] matrix){
        int len = matrix.length * matrix[0].length;
        int[] res = new int[len];

        int x=0, y=0, offset=1, loop = matrix.length / 2, count=0;

        while (loop > 0){
            int tmp_x = x;
            int tmp_y = y;

            for (; tmp_y < y+matrix.length-offset; tmp_y++){
                res[count++] = matrix[tmp_x][tmp_y];
            }
            for (; tmp_x < x+matrix.length-offset; tmp_x++){
                res[count++] = matrix[tmp_x][tmp_y];
            }
            for (; tmp_y > y; tmp_y--){
                res[count++] = matrix[tmp_x][tmp_y];
            }
            for (; tmp_x > x; tmp_x--){
                res[count++] = matrix[tmp_x][tmp_y];
            }
            if (--loop == 0 && matrix.length % 2 == 1){
                res[count] = matrix[matrix.length / 2][matrix.length / 2];
            }
            x++; y++; offset += 2;
        }
        return res;
    }

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        int[] res = solution(matrix);
        System.out.println(Arrays.toString(res));
    }

}
